/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.plan.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.javaeye.common.util.DateUtils;
import com.javaeye.delivery.dto.CustomerOrder;
import com.javaeye.delivery.dto.OrderDetail;
import com.javaeye.delivery.service.IOrderService;
import com.javaeye.delivery.web.OrderCondition;
import com.javaeye.plan.dto.MonthPlanDetail;
import com.javaeye.plan.dto.PlanDetailOrderInfo;
import com.javaeye.plan.service.IMonthPlanService;
import com.javaeye.store.dto.Materials;
import com.javaeye.store.service.MaterialsService;

public class MonthPlanAction extends ActionSupport {
	
	protected static Log log = LogFactory.getLog(MonthPlanAction.class); 
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3216585574200112708L;

	/**
	 * 用于显示一览结果集
	 */
	private List<MonthPlanDetail> planDetails;
	
	private List<Integer> productIds;
	
	private List<Integer> planNums;
	
	private List<String> batchNos;
	
	private List<String> rootCategoryNames;
	
	private List<String> categoryNames;
	
	private String queryDate;
	
	private List<Integer> detailIds;
	
	private String removeDetailIds;
	
	private List<String> productSkus;
	
	private List<String> productNos;
	
	/**
	 * Service
	 */
	private IMonthPlanService service;
	
	private IOrderService orderService;
	
	private MaterialsService materialsService;
	
	public void setService(IMonthPlanService service) {
		this.service = service;
	}

	public void setOrderService(IOrderService orderService) {
		this.orderService = orderService;
	}

	public void setMaterialsService(MaterialsService materialsService) {
		this.materialsService = materialsService;
	}

	public MonthPlanAction() {
		productIds = new ArrayList<Integer>();
		queryDate = DateUtils.dateToString("yyyy-MM");
	}
	
	/**
	 * 查询月度计划明细
	 * @return
	 * @throws Exception
	 */
	public String queryPlanDetailInfo() throws Exception {
		//Date date = DateUtils.stringToDate(queryDate, "yyyy-MM");
		planDetails = service.getPlanDetailInfo(queryDate);
		return SUCCESS;
	}
	
	/**
	 * 查询用于生成月度计划明细
	 * @return
	 * @throws Exception
	 */
	public String queryOrderDetailForMonthPlan() throws Exception {
		//Date date = DateUtils.stringToDate(queryDate, "yyyy-MM");
		planDetails = service.getPlanDetailInfo(queryDate);
		if (planDetails.size() > 0) {
			return "edit";
		}
		
		
		//查询已经安排计划到等待理货的所有出货单明细
		OrderCondition condition = new OrderCondition();
		condition.setStatus(new Integer[]{CustomerOrder.ORDER_STATES_PLAN,
				CustomerOrder.ORDER_STATES_BUSINESS});
		List<CustomerOrder> orderList = orderService.getOrderList(condition);
		Map<Integer, MonthPlanDetail>planDetailMap = new HashMap<Integer, MonthPlanDetail>();
		for (CustomerOrder order : orderList) {
			order = orderService.getOrderBaseInfo(order.getId());
			Set<OrderDetail> details = order.getOrderDetails();
			for (OrderDetail detail : details) {
				int productId = detail.getProductId();
				MonthPlanDetail planDetail = planDetailMap.get(productId);
				if (planDetail == null) {
					planDetail = initPlanDetail(detail);
					planDetailMap.put(productId, planDetail);
				}
				PlanDetailOrderInfo orderInfo = new PlanDetailOrderInfo();
				orderInfo.setOrderId(order.getId());
				orderInfo.setNumber(detail.getNumber());
				orderInfo.setFinishDate(detail.getFinishDate());
				planDetail.addOrderInfo(orderInfo);
			}
		}
		//根据产品ID排序
		Collection<MonthPlanDetail> palnDetails = planDetailMap.values();
		MonthPlanDetail[] planDetailArray = palnDetails.toArray(new MonthPlanDetail[palnDetails.size()]);
		Arrays.sort(planDetailArray, new Comparator<MonthPlanDetail>() {
			@Override
			public int compare(MonthPlanDetail object1, MonthPlanDetail object2) {
				return  object1.getProductId() - object2.getProductId();
			}
		});
		planDetails = Arrays.asList(planDetailArray);
		return SUCCESS;
	}
	
	private MonthPlanDetail initPlanDetail(OrderDetail detail) {
		MonthPlanDetail planDetail = new MonthPlanDetail();
		planDetail.setProductId(detail.getProductId());
		planDetail.setProductName(detail.getProductName());
		planDetail.setProductRootCategory(detail.getProductRootCategory());
		planDetail.setProductCategory(detail.getProductCategory());
		planDetail.setProductType(detail.getProductType());
		planDetail.setProductNo(detail.getProductNo());
		planDetail.setCustomNo(detail.getCustomNo());
		planDetail.setUnit(detail.getUnit());
		planDetail.setAcceptNumber(detail.getAcceptNumber());
		planDetail.setProductSku(detail.getProductSku());
		return planDetail;
	}
	
	/**
	 * 保存
	 * @return
	 * @throws Exception
	 */
	public String saveMonthPlan() throws Exception {
		Set<String> planDetailSet = new HashSet<String>();
		List<MonthPlanDetail> saveList = new ArrayList<MonthPlanDetail>();
		for (int i = 0; i < productIds.size(); i++) {
			int number = planNums.get(i);
			if (number > 0) {
				//检查明细是否有重复
				String batchNo = batchNos.get(i).trim();
				int productId = productIds.get(i);
				String notSameCheck =  batchNo + "," + productId;
				if (planDetailSet.contains(notSameCheck)) {
					List<Object> params = new ArrayList<Object>();
					params.add("计划明细");
					this.addActionError(getText("actionErrorSaveSameRecord", params));
					queryOrderDetailForMonthPlan();
					return INPUT;
				}
				planDetailSet.add(notSameCheck);
				
				String productNo = productNos.get(i);
				Materials materials = materialsService.getMaterialsByCode(productNo);
				MonthPlanDetail planDetail = new MonthPlanDetail();
				planDetail.setMonthNo(queryDate);
				planDetail.setProductId(productId);
				planDetail.setProductNo(productNo);
				planDetail.setProductRootCategory(rootCategoryNames.get(i));
				planDetail.setProductCategory(categoryNames.get(i));
				planDetail.setProductName(materials.getName());
				planDetail.setProductType(materials.getType());
				planDetail.setProductSku(productSkus.get(i));
				planDetail.setUnit(materials.getUnits());
				planDetail.setNumber(number);
				planDetail.setBatchNo(batchNo);
				
				if (detailIds != null && detailIds.size() > 0) {
					if (i < detailIds.size()) {
						planDetail.setId(detailIds.get(i));
					}
				}
				saveList.add(planDetail);
			}
		}
//		for (MonthPlanDetail detail : saveList) {
//			log.debug("MonthPlanAction:id=" + detail.getId() + ",ProductId=" + detail.getProductId()
//					 + ",BatchNo=" + detail.getBatchNo() + ",Number=" + detail.getNumber());
//		}
//		log.debug("MonthPlanAction:removeDetailIds=" + removeDetailIds);
		if (removeDetailIds == null || "".equals(removeDetailIds.trim())) {
			service.saveMonthPlanList(saveList, null);
		} else {
			String[] detailIds = removeDetailIds.split(",");
			service.saveMonthPlanList(saveList, detailIds);
		}

		return SUCCESS;
	}

	public List<MonthPlanDetail> getPlanDetails() {
		return planDetails;
	}

	public void setPlanDetails(List<MonthPlanDetail> planDetails) {
		this.planDetails = planDetails;
	}

	public List<Integer> getProductIds() {
		return productIds;
	}

	public void setProductIds(List<Integer> productIds) {
		this.productIds = productIds;
	}

	public List<Integer> getPlanNums() {
		return planNums;
	}

	public void setPlanNums(List<Integer> planNums) {
		this.planNums = planNums;
	}

	public List<String> getRootCategoryNames() {
		return rootCategoryNames;
	}

	public void setRootCategoryNames(List<String> rootCategoryNames) {
		this.rootCategoryNames = rootCategoryNames;
	}

	public List<String> getCategoryNames() {
		return categoryNames;
	}

	public void setCategoryNames(List<String> categoryNames) {
		this.categoryNames = categoryNames;
	}

	public String getQueryDate() {
		return queryDate;
	}

	public void setQueryDate(String queryDate) {
		this.queryDate = queryDate;
	}

	public List<String> getBatchNos() {
		return batchNos;
	}

	public void setBatchNos(List<String> batchNos) {
		this.batchNos = batchNos;
	}

	public List<Integer> getDetailIds() {
		return detailIds;
	}

	public void setDetailIds(List<Integer> detailIds) {
		this.detailIds = detailIds;
	}

	public String getRemoveDetailIds() {
		return removeDetailIds;
	}

	public void setRemoveDetailIds(String removeDetailIds) {
		this.removeDetailIds = removeDetailIds;
	}

	public List<String> getProductSkus() {
		return productSkus;
	}

	public void setProductSkus(List<String> productSkus) {
		this.productSkus = productSkus;
	}

	public List<String> getProductNos() {
		return productNos;
	}

	public void setProductNos(List<String> productNos) {
		this.productNos = productNos;
	}

}
